package org.tulkas.selector.pattern;

import java.util.Collection;
import java.util.TreeSet;

import org.tulkas.selector.Filter;
import org.tulkas.selector.FilterComparator;
import org.w3c.dom.Element;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
public class Group implements Filter {
	private TreeSet<Filter> filters = new TreeSet<Filter>(new FilterComparator(
			true));

	public Group(Collection<Filter> filters) {
		if (filters == null || filters.size() == 0) {
			throw new IllegalArgumentException(
					"A group must contain at least 1 filter");
		}
		this.filters.addAll(filters);
	}

	/* (non-Javadoc)
	 * @see org.tulkas.selector.Filter#getPriority()
	 */
	@Override
	public int getPriority() {
		return filters.iterator().next().getPriority();
	}

	/* (non-Javadoc)
	 * @see org.tulkas.selector.Filter#matches(org.w3c.dom.Element)
	 */
	@Override
	public boolean matches(Element element) {
		for (Filter filter : filters) {
			if (filter.matches(element)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();

		int i = 0;
		for (Filter filter : filters) {
			if (i > 0) {
				sb.append(" | ");
			}
			sb.append("(").append(filter.toString()).append(")");
		}
		return sb.toString();
	}

}
